﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PhotoOfTheDay.Types;
using System.IO;

namespace PhotoOfTheDay
{
    public partial class Archiver : Form
    {
        private delegate void UpdateInvoker();

        public Archiver()
        {
            InitializeComponent();
        }

        private void Archiver_Load(object sender, EventArgs e)
        {
            StartDate.MinDate = new DateTime(DateTime.Today.Year - 3, 1, 1);
            StartDate.MaxDate = DateTime.Today.AddDays(-2);
            StartDate.Value = DateTime.Today.AddMonths(-1);
            EndDate.MinDate = new DateTime(DateTime.Today.Year - 3, 1, 2);
            EndDate.MaxDate = DateTime.Today.AddDays(-1);
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
            }
            base.OnFormClosing(e);
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            if (Global.PhotoArchiver != null && Global.PhotoArchiver.IsAlive)
            {
                Global.PhotoArchiver.Abort();
                running = false;
            }
            else
            {
                if ((EndDate.Value - StartDate.Value).TotalDays < 1)
                {
                    MessageBox.Show("End date must be later than start date", "Invalid Request", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //Initialize variables
                TotalCount = (int)((EndDate.Value - StartDate.Value).TotalDays) + 1;
                Archived = 0;
                CurrentPhoto = null;

                //Start thread
                Global.PhotoArchiver = new System.Threading.Thread(ArchiverThread);
                Global.PhotoArchiver.Start();
                running = true;
            }
            UpdateUI();
        }

        int TotalCount = 100;
        int Archived = 0;
        Bitmap CurrentPhoto = null;

        bool running = false;

        private void ArchiverThread()
        {
            running = true;
            UpdateInvoker UIUpdater = new UpdateInvoker(UpdateUI);
            string EntranceURL = GetEntranceURL();

            Photo photo = new Photo();

            if (EntranceURL != null)
            {
                photo = Photo.Navigate(EntranceURL, true);
                LoadPhoto(photo);
                Archived = 1;
                this.Invoke(UIUpdater);

                for (Archived = 2; Archived <= TotalCount; Archived++)
                {
                    if (!photo.NextAvailable) break;
                    photo = Photo.Navigate(photo.NextLink, true);
                    LoadPhoto(photo);
                    this.Invoke(UIUpdater);
                }
            }
            running = false;
            this.Invoke(UIUpdater);
        }

        private void LoadPhoto(Photo photo)
        {
            string mypicture = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures);
            mypicture = Path.Combine(mypicture, "Photo of the Day");
            if (!Directory.Exists(mypicture))
            {
                Directory.CreateDirectory(mypicture);
            }
            mypicture = Path.Combine(mypicture, photo.photoDate.ToMonthName() + " " + photo.photoDate.Day + ", " + photo.photoDate.Year + " - " + photo.PhotoName + ".bmp");
            if (File.Exists(mypicture))
            {
                FileStream str = File.OpenRead(mypicture);
                CurrentPhoto = (Bitmap)Bitmap.FromStream(str);
                str.Close();
            }
        }

        private string GetEntranceURL()
        {
            string temp = Global.GetHTTPData(Global.ArchiveURL + "month=" + StartDate.Value.Month + "&page=1&year=" + StartDate.Value.Year);

            //Dig into the focus
            temp= Scraper.GetAfter(temp,"<div id=\"search_results\" class=\"thumbnail_grid\">");
            temp = Scraper.GetBefore(temp, "Photo of the Day, " + StartDate.Value.ToMonthName() + " " + StartDate.Value.Day + ", " + StartDate.Value.Year);
            temp = Scraper.GetAfterLast(temp, ">View Photo &raquo;</a>");
            temp = Scraper.GetAnchorURL(temp);
            temp = Global.BaseURL + temp;
            return temp;
        }

        private void UpdateUI()
        {
            if (!running)
            {
                StartDate.Enabled = true;
                EndDate.Enabled = true;
                StartButton.Text = "Start";
                DownloadProgress.Value = 0;
                DownloadProgress.Visible = false;
                StatusLabel.Text = "Ready";
            }
            else
            {
                StartDate.Enabled = false;
                EndDate.Enabled = false;
                StartButton.Text = "Stop";
                int Percentage = (int)(((double)Archived / (double)TotalCount) * 100);
                DownloadProgress.Value = Percentage;
                DownloadProgress.Visible = true;
                StatusLabel.Text = "(" + Archived + "/" + TotalCount + ")";
            }
            PhotoOfTheDay.SizeMode = PictureBoxSizeMode.Zoom;
            PhotoOfTheDay.Image = CurrentPhoto;
        }

    }
}
